package com.example.demo.service.impl;

import com.example.demo.entity.LoginTicket;
import com.example.demo.entity.User;
import com.example.demo.mapper.LoginTicketMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LoginTicketMapper loginTicketMapper;

    public int insertUser(User user) {
        return userMapper.insert(user);
    }

    public int deleteUserById(Integer id) {
        return userMapper.deleteById(id);
    }

    public int updateUserById(User user) {
        return userMapper.updateById(user);
    }

    public User selectUserById(Integer id) {
        return userMapper.selectById(id);
    }

    //登录
    public Map<String, String> login(String username, String password) {
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isBlank(username)) {
            map.put("error", "账号不能为空");
            return map;
        }
        HashMap<String, Object> columnMap = new HashMap<>();
        columnMap.put("username", username);
        List<User> users = userMapper.selectByMap(columnMap);
        if (users.isEmpty()) {
            map.put("error", "找不到该用户");
            return map;
        }
        User user = users.get(0);
        if (user.getPassword().equals(password)) {
            LoginTicket loginTicket = new LoginTicket();
            loginTicket.setTicket(UUID.randomUUID().toString());
            loginTicket.setUserId(user.getId());
            loginTicket.setStatus(1);
            loginTicketMapper.insert(loginTicket);
            map.put("ticket", loginTicket.getTicket());
            //TODO 此处可改成用redis，不应该直接用mysql,redis还可以设置过期时间
        } else {
            map.put("error", "密码不正确");
        }


        return map;

    }

    @Override
    public String logout(String ticket) {
        //此处redis本来自带过期时间，且一个key对应一个登录凭证
        //用mysql会频繁生成多次凭证，而且不能设置过期时间
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("ticket", ticket);
        columnMap.put("status", 1);
        List<LoginTicket> loginTickets = loginTicketMapper.selectByMap(columnMap);
        if (loginTickets.isEmpty()) {
            return "该账号登录状态已失效";
        }
        LoginTicket loginTicket = loginTickets.get(0);
        loginTicket.setStatus(0);
        loginTicketMapper.updateById(loginTicket);
        return "已登出";

    }
}
